"this is the locale selecting middleware that will look at accept headers"

from django.utils.cache import patch_vary_headers
from django.utils import translation as trans_real
from eventr import trans_fixed as translation
from django.middleware.locale import LocaleMiddleware
from django.http import HttpResponseRedirect


class MyLocaleMiddleware(LocaleMiddleware):
    """
    	There is an error in LocaleMiddleware which makes unable dynamic switching of languages.
    	We need to fix it.
    """

    def process_request(self, request):
        language = translation.get_language_from_request(request)
        trans_real.activate(language)
        request.LANGUAGE_CODE = translation.get_language()


def set_language(request):
    """
    Redirect to a given url while setting the chosen language in the
    session or cookie. The url and the language code need to be
    specified in the GET parameters.
    """
    lang_code = request.GET.get('language', None)
    next = request.GET.get('next', None)
    if not next:
        next = request.META.get('HTTP_REFERER', None)
    if not next:
        next = '/'
    response = HttpResponseRedirect(next)
    if lang_code and translation.check_for_language(lang_code):
        if hasattr(request, 'session'):
            request.session['django_language'] = lang_code
        else:
            response.set_cookie('django_language', lang_code)
    return response
